package com.fit4as.fit
{

// Copyright (c) 2002 Cunningham & Cunningham, Inc.
// Released under the terms of the GNU General Public License version 2 or later.

import com.fit4as.util.reflect.Method;
import com.fit4as.util.reflect.ClassUtil;
import flash.utils.getDefinitionByName;

public class ActionFixture extends Fixture {

    protected var cells : Parse;
    public static var actor : Fixture; // actor is static to keep it between instantiations
    protected static var empty : Array = [];

    // Traversal ////////////////////////////////

    /**
     * find out which action the first cell contains and execute it
     */
    override public function doCells( cells : Parse ) : void 
    {
        //t race("ActionFixture#doCells " + cells.text() );
        this.cells = cells;

        try {
            var action : Method = ClassUtil.getMethod( ClassUtil.getClass( this ), cells.text(), empty );
            action.invoke( this, empty );
        } catch( e : Error ) {
            exception( cells, e );
        }
    }

    // Actions //////////////////////////////////

    /**
     * create an instance of the actor fixture
     */
    public function start() : void 
    {
        var className : String = cells.more.text();
		//t race("ActionFixture#start className: " + className );        
        var classObject : Class = ClassUtil.getClassByName( className );
        //t race("ActionFixture#start classObject: " + classObject );        
        actor = Fixture( new classObject() );
        //t race("ActionFixture#start actor:" + actor);
    }

    public function enter() : void 
    {
        var method : Method = this.method();
        var type : Class = Class( method.getParameterTypes()[0] );
        var text : String = cells.more.more.text();
        var args : Array = [ TypeAdapter.on( actor, type ).parse( text )];
        //t race("ActionFixture#enter " + [method.getName(), args, text, type ]);
        method.invoke( actor, args );
    }

    public function press() : void {
        method().invoke( actor, empty );
    }

    override public function check( ... ignore ) : void {
        var adapter : TypeAdapter = TypeAdapter.onMethod( actor, method() );
        super.check( cells.more.more, adapter );
    }

    // Utility //////////////////////////////////

    protected function method( name : String = null): Method 
    {
        if (name == null) name = camel( cells.more.text() );

        var result : Method = ClassUtil.getMethod( ClassUtil.getClass( actor ), name );
        if ( result == null ) throw new NoSuchMethodException();
        return result;
    }
}
}